<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { addAppoint, editAppoint, getAppointList } from '@/api/me/more'
import { useUserStore } from '@/store'

definePage({
  style: {
    navigationBarTitleText: '预约管理',
  },
})
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 预约列表数据
const appointmentList = ref<any[]>([])
// 当前选中的日期，默认为今天（时间戳格式）
const selectedDate = ref<number>(Date.now())

// 弹窗相关状态
const isPopupVisible = ref(false)
const selectedTimeSlot = ref<string>('')
const appointmentCount = ref<number | null>(null)
// 开始时间和结束时间（时分表示）
const startTime = ref<string>('09:00')
const endTime = ref<string>('10:00')
// 当前编辑的预约项ID（null表示新增）
const editingAppointmentId = ref<number | null>(null)
// 将时间戳转换为YYYY-MM-DD格式字符串
function timestampToDateString(timestamp: number): string {
  // 创建日期对象
  const date = new Date(timestamp)

  // 获取年、月、日（使用UTC方法避免时区问题）
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 返回YYYY-MM-DD格式字符串
  return `${year}-${month}-${day}`
}

// 获取今日日期（时间戳格式）
function getTodayDate(): number {
  return Date.now()
}

// 获取指定日期的结束时间戳（当天23:59:59）
function getEndOfDay(date: Date): number {
  const endOfDay = new Date(date)
  endOfDay.setHours(23, 59, 59, 999)
  return endOfDay.getTime()
}

// 获取日历最大可选日期（30天后）
function getMaxDate(): number {
  const maxDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
  return getEndOfDay(maxDate)
}

// 加载预约列表数据
onLoad(async () => {
  const res = await getAppointList({ userId: userInfo.value.userId, zhuanjiaId: userInfo.value.userId })
  console.log('getAppointList', res)
  if (res.length) {
    appointmentList.value = res
  }
})

// 处理日期选择
function handleDateSelect({ value }: { value: number }) {
  console.log('handleDateSelect', value)
  selectedDate.value = value
}

// 打开弹窗 - 支持新增或编辑模式
function openPopup() {
  // 新增模式时重置表单
  if (editingAppointmentId.value === null) {
    selectedTimeSlot.value = ''
    appointmentCount.value = null
    startTime.value = '09:00'
    endTime.value = '10:00'
    // 默认选择今天
    selectedDate.value = Date.now()
  }
  isPopupVisible.value = true
}

// 关闭弹窗
function closePopup() {
  isPopupVisible.value = false
  // 关闭时重置编辑状态
  editingAppointmentId.value = null
  console.log('closePopup', editingAppointmentId.value)
}
// 编辑预约项
function editAppointment(item: any) {
  // 设置编辑状态
  editingAppointmentId.value = item.id

  // 回显数据到表单
  // 转换日期字符串为时间戳
  const date = new Date(item.date)
  selectedDate.value = date.getTime()

  // 分割时间段为开始时间和结束时间
  if (item.timeSlot) {
    const [start, end] = item.timeSlot.split('-')
    startTime.value = start
    endTime.value = end
    selectedTimeSlot.value = item.timeSlot
  }

  // 回显可预约号数
  appointmentCount.value = item.kyySlots

  // 打开弹窗
  openPopup()
}

// 将时间字符串（格式：HH:MM）转换为分钟数
function timeStringToMinutes(timeStr: string): number {
  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours * 60 + minutes
}

// 提交表单
async function submitForm() {
  // 组合开始时间和结束时间
  if (startTime.value && endTime.value) {
    // 检查结束时间是否小于开始时间
    // 将时间字符串转换为分钟数进行比较
    const startTimeMinutes = timeStringToMinutes(startTime.value)
    const endTimeMinutes = timeStringToMinutes(endTime.value)

    if (endTimeMinutes <= startTimeMinutes) {
      uni.showToast({
        title: '结束时间不能小于或等于开始时间',
        icon: 'none',
      })
      return
    }

    selectedTimeSlot.value = `${startTime.value}-${endTime.value}`
  }
  else {
    uni.showToast({
      title: '请选择完整的时间段',
      icon: 'none',
    })
    return
  }

  if (appointmentCount.value === null || appointmentCount.value <= 0) {
    uni.showToast({
      title: '请输入有效的可预约号数',
      icon: 'none',
    })
    return
  }

  // 收集数据
  const dateStr = timestampToDateString(selectedDate.value)
  const appointmentData = {
    // id: editingAppointmentId.value,
    zhuanjiaId: userInfo.value.userId,
    date: dateStr,
    timeSlot: selectedTimeSlot.value,
    kyySlots: appointmentCount.value,
  }

  // 打印数据
  console.log(appointmentData)
  const res = await (editingAppointmentId.value ? editAppoint({ id: editingAppointmentId.value, ...appointmentData }) : addAppoint(appointmentData))
  console.log('addAppoint', res)
  // 显示成功提示
  uni.showToast({
    title: editingAppointmentId.value ? '修改成功' : '添加成功',
    icon: 'success',
  })

  // 关闭弹窗
  closePopup()

  // 重新加载预约列表
  const refreshRes = await getAppointList({ userId: userInfo.value.userId, zhuanjiaId: userInfo.value.userId })
  if (refreshRes.length) {
    appointmentList.value = refreshRes
    editingAppointmentId.value = null
  }
}
</script>

<template>
  <view class="page-container">
    <!-- 顶部标题 -->
    <!-- <view class="page-header">
            <text class="page-title">预约管理</text>
        </view> -->

    <!-- 预约列表 -->
    <view class="appointment-list">
      <view v-if="appointmentList.length === 0" class="empty-tip">
        <text>暂无预约安排</text>
      </view>
      <view v-else class="appointment-items">
        <view
          v-for="item in appointmentList" :key="item.id" class="appointment-item"
          @click="editAppointment(item)"
        >
          <view class="item-header">
            <text class="item-date">{{ item.date }}</text>
            <text
              class="item-state" :class="{
                'state-available': item.state === 1,
                'state-unavailable': item.state === 0,
                'state-full': item.state === 2,
              }"
            >
              {{ item.state === 1 ? '可预约' : item.state === 0 ? '不可预约' : '已约满' }}
            </text>
          </view>
          <view class="item-content">
            <view class="item-time">
              时间段：{{ item.timeSlot }}
            </view>
            <view class="item-slots">
              <text>可预约号数：{{ item.kyySlots }}</text>
              <text v-if="item.yyySlots > 0" class="booked-slots">已预约：{{ item.yyySlots }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 新增/修改按钮 -->
    <view class="add-button-container">
      <button class="add-button" @click="openPopup">
        新增预约
      </button>
    </view>

    <!-- 弹窗 -->
    <wd-popup v-model="isPopupVisible" position="bottom" :closable="true" :mask-close-able="false" @close="closePopup">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ editingAppointmentId ? '修改预约' : '新增预约' }}</text>
          <!-- <text class="popup-close" @click="closePopup">×</text> -->
        </view>

        <view class="popup-body">
          <!-- 在弹窗内添加日历选择器 -->
          <view class="date-picker-container">
            <text class="section-title">选择日期：</text>
            <wd-calendar
              v-model="selectedDate" mode="single" :min-date="getTodayDate()"
              :max-date="getMaxDate()" @confirm="handleDateSelect"
            />
          </view>

          <view class="selected-date">
            <text>已选择日期：{{ timestampToDateString(selectedDate) }}</text>
          </view>

          <view class="time-slot-container">
            <text class="section-title">选择时间段：</text>
            <!-- 左侧开始时间选择器 -->
            <view class="time-picker-wrapper">
              <wd-datetime-picker v-model="startTime" type="time" minute-step="30" class="time-picker" />

              <!-- 连接符 -->
              <view class="time-separator">
                -
              </view>

              <!-- 右侧结束时间选择器 -->
              <wd-datetime-picker v-model="endTime" type="time" minute-step="30" class="time-picker" />
            </view>

            <!-- 显示已选择的时间段 -->
            <view v-if="startTime && endTime" class="selected-time">
              已选择：{{ startTime }}-{{ endTime }}
            </view>
          </view>

          <view class="count-input-container">
            <text class="section-title">可预约号数：</text>
            <input
              v-model.number="appointmentCount" type="number" placeholder="请输入可预约号数"
              class="count-input" min="1"
            >
          </view>
        </view>

        <view class="popup-footer">
          <button class="submit-button" @click="submitForm">
            {{ editingAppointmentId ? '确认修改' : '确认添加'
            }}
          </button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style scoped>
/* 为预约项添加点击效果 */
.appointment-item {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  /* 添加点击效果 */
  transition: all 0.3s ease;
}

.appointment-item:active {
  background-color: #f5f5f5;
  transform: scale(0.98);
}
/* 页面容器 */
.page-container {
  padding: 20rpx;
  box-sizing: border-box;
  padding-bottom: 100rpx;
}

/* 顶部标题 */
.page-header {
  margin-bottom: 30rpx;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
}

/* 预约列表 */
.appointment-list {
  min-height: 400rpx;
}

.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.appointment-items {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.appointment-item {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.item-date {
  font-size: 32rpx;
  font-weight: bold;
}

.item-state {
  font-size: 28rpx;
  padding: 6rpx 20rpx;
  border-radius: 20rpx;
}

.state-available {
  background-color: #e6f7ff;
  color: #1890ff;
}

.state-unavailable {
  background-color: #f5f5f5;
  color: #999;
}

.state-full {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.item-time {
  font-size: 30rpx;
}

.item-slots {
  display: flex;
  gap: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.booked-slots {
  color: #ff4d4f;
}

/* 新增/修改按钮 */
.add-button-container {
  position: fixed;
  bottom: 20rpx;
  left: 20rpx;
  right: 20rpx;
}

.add-button {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
}

/* 弹窗样式 */
.popup-content {
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 34rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 48rpx;
  color: #999;
}

.popup-body {
  padding: 30rpx;
}

.date-picker-container {
  margin-bottom: 30rpx;
}

.selected-date {
  margin-bottom: 30rpx;
  padding: 10rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

/* 时间段选择器样式 */
.time-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.time-picker {
  flex: 1;
}

.time-separator {
  font-size: 32rpx;
  font-weight: bold;
  color: #666;
}

/* 已选时间段显示样式 */
.selected-time {
  margin-top: 15rpx;
  padding: 10rpx;
  background-color: #e6f7ff;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #1890ff;
  text-align: center;
}

.count-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 30rpx;
}

.popup-footer {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.submit-button {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
}
</style>
